package com.rongmei.jdsync.service;


import com.rongmei.jdsync.client.MallGoodsFeignApi;
import com.rongmei.jdsync.dto.BaseResponseDto;
import com.rongmei.jdsync.dto.RBase;
import com.rongmei.jdsync.entity.Goods;
import com.rongmei.jdsync.entity.JdSyncLog;
import com.rongmei.jdsync.entity.SkuData;
import com.rongmei.jdsync.entity.enums.OperationType;
import com.rongmei.jdsync.repository.GoodsRepository;
import com.rongmei.jdsync.repository.SkuDataRepository;
import com.rongmei.jdsync.util.SyncLogUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author dongjun
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class JdSupplierSyncService {

    private static final int GOODS_ON_SHELF_STATE = 1;
    private static final int GOODS_STATE_OFF_SHELF = 0;

    private final GoodsRepository goodsRepository;
    private final SyncLogUtils syncLogUtils;
    private final SkuDataRepository skuDataRepository;
    private final MallGoodsFeignApi mallGoodsFeignApi;

    /**
     * 更新商品状态
     *
     * @param goodsId    商品ID
     * @param skuId      SKU ID，如果为null则表示是商品级别的操作
     * @param goodsState 商品状态，0表示下架，1表示上架
     * @param operator   操作人
     * @return BaseResponseDto 响应对象
     * @throws IllegalArgumentException 如果商品状态值无效（只允许0或1）
     * @throws RuntimeException         如果商品不存在
     */
    @Transactional
    public BaseResponseDto<?> updateGoodsState(Long goodsId, Long skuId, Integer goodsState, String operator) {
        OperationType operationType = skuId != null ?
                (goodsState == 1 ? OperationType.SKU_ON_SHELF : OperationType.SKU_OFF_SHELF) :
                (goodsState == 1 ? OperationType.GOODS_ON_SHELF : OperationType.GOODS_OFF_SHELF);

        JdSyncLog jdSyncLog = syncLogUtils.startLog(goodsId, skuId, operationType, operator);
        jdSyncLog.setGoodsState(goodsState);

        try {
            // 验证状态值
            if (goodsState != 0 && goodsState != 1) {
                throw new IllegalArgumentException("商品状态值无效，只允许0(下架)或1(上架)");
            }

            // 获取商品
            Goods goods = goodsRepository.findByGoodsId(goodsId);
            if (goods == null) {
                throw new RuntimeException("商品不存在");
            }

            // 状态变更逻辑
            if (goodsState == 0) {
                handleOffShelf(goodsId, skuId, goods);
            } else {
                handleOnShelf(goodsId, skuId, goods);
            }

            // 推送状态变更
            pushStateToGoodsService(goodsId, goodsState);
            // 记录成功日志
            syncLogUtils.successLog(jdSyncLog, "状态更新成功");
            return BaseResponseDto.success("状态更新成功");
        } catch (Exception e) {
            // 记录失败日志
            syncLogUtils.failLog(jdSyncLog, e);
            return BaseResponseDto.error(e.getMessage());
        }
    }


    /**
     * 处理商品下架操作
     *
     * @param goodsId 商品ID
     * @param skuId   SKU ID，如果为null表示商品下架，不为null表示单个SKU下架
     * @param goods   商品对象
     */
    private void handleOffShelf(Long goodsId, Long skuId, Goods goods) {
        if (goods == null || goodsId == null) {
            log.warn("handleOffShelf方法参数无效，goodsId: {}, goods: {}", goodsId, goods);
            return;
        }

        try {
            if (skuId == null) {
                log.info("开始处理商品下架操作，商品ID: {}", goodsId);
                handleGoodsOffShelf(goodsId, goods);
            } else {
                log.info("开始处理单个SKU下架操作，商品ID: {}, SKU ID: {}", goodsId, skuId);
                handleSingleSkuOffShelf(goodsId, skuId, goods);
            }
            goodsRepository.save(goods);
            log.debug("商品下架操作成功后保存商品，商品ID: {}", goodsId);
        } catch (Exception e) {
            log.error("处理商品下架操作失败，商品ID: {}, SKU ID: {}", goodsId, skuId, e);
            throw e;
        }
    }


    /**
     * 处理商品下架操作
     *
     * @param goodsId 商品ID
     * @param goods   商品对象
     */
    private void handleGoodsOffShelf(Long goodsId, Goods goods) {
        List<SkuData> skus = skuDataRepository.findSkuDatasByGoodsIdIn(Collections.singletonList(goodsId));
        skus.forEach(sku -> sku.setGoodsState(GOODS_STATE_OFF_SHELF));
        skuDataRepository.saveAll(skus);
        goods.setGoodsState(GOODS_STATE_OFF_SHELF);
    }

    /**
     * 处理单个SKU下架
     *
     * @param goodsId 商品ID
     * @param skuId   SKU ID
     * @param goods   商品实体
     */
    private void handleSingleSkuOffShelf(Long goodsId, Long skuId, Goods goods) {
        Optional<SkuData> currentSku = skuDataRepository.findBySkuId(skuId);
        if (!currentSku.isPresent()) {
            log.warn("未找到指定的SKU，SKU ID: {}", skuId);
            return;
        }

        SkuData sku = currentSku.get();
        sku.setGoodsState(GOODS_STATE_OFF_SHELF);
        skuDataRepository.save(sku);
        log.info("SKU下架成功，SKU ID: {}", skuId);

        boolean allSkusOff = skuDataRepository.findSkuDatasByGoodsIdIn(Collections.singletonList(goodsId))
                .stream()
                .filter(skuData -> !skuData.getSkuId().equals(skuId))
                .allMatch(skuData -> skuData.getGoodsState() == GOODS_STATE_OFF_SHELF);

        if (allSkusOff) {
            goods.setGoodsState(GOODS_STATE_OFF_SHELF);
            log.info("该商品的所有SKU均已下架，商品ID: {}", goodsId);
        }
    }


    /**
     * 处理商品上架
     *
     * @param goodsId 商品ID
     * @param skuId   SKU ID
     * @param goods   商品对象
     */
    @Transactional
    public void handleOnShelf(Long goodsId, Long skuId, Goods goods) {
        log.info("开始处理商品上架操作，商品ID: {}, SKU ID: {}", goodsId, skuId);
        goods.setGoodsState(GOODS_ON_SHELF_STATE);
        if (skuId != null) {
            Optional<SkuData> currentSku = skuDataRepository.findBySkuId(skuId);
            if (currentSku.isPresent()) {
                SkuData sku = currentSku.get();
                sku.setGoodsState(GOODS_ON_SHELF_STATE);
                skuDataRepository.save(sku);
                log.info("SKU上架成功，SKU ID: {}", skuId);
            }
        } else {
            //所有SKU状态更新
            List<SkuData> skus = skuDataRepository.findSkuDatasByGoodsIdIn(Collections.singletonList(goodsId));
            skus.forEach(sku -> {
                sku.setGoodsState(GOODS_ON_SHELF_STATE);
                skuDataRepository.save(sku);
            });
        }
        goodsRepository.save(goods);
        log.info("商品上架成功，商品ID: {}", goodsId);
    }


    /**
     * 将商品状态推送到商品服务
     *
     * @param goodsId    商品ID
     * @param goodsState 商品状态
     * @throws RuntimeException 商品状态推送异常
     */
    private void pushStateToGoodsService(Long goodsId, Integer goodsState) {
        try {
            // 1:本地状态 2:上架 3:下架
            Integer pushStatus = goodsState == 1 ? 2 : 3;
            RBase result = mallGoodsFeignApi.goodsPutOff(goodsId.toString(), pushStatus);
            if (result.getStatus() != 200) {
                throw new RuntimeException("商品状态推送失败: " + result.getMsg());
            }
        } catch (Exception e) {
            log.error("商品状态推送异常", e);
            throw new RuntimeException("商品状态推送异常: " + e.getMessage());
        }
    }
}